package code.whmmm.util.spring.quartz;

import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.spi.JobFactory;
import org.quartz.spi.TriggerFiredBundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import code.whmmm.util.spring.util.SpringBeanUtil;

/**
 * <p><b>
 *
 * </b></p>
 * <br/>
 * 创建时间: 8/14/2019 1:20 PM
 *
 * @author Zero
 */
@Component
public class QuartzJobFactory implements JobFactory {

    private final Logger log = LoggerFactory.getLogger(getClass());


    @Override
    public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler) throws SchedulerException {
        JobDetail jobDetail = bundle.getJobDetail();
        Class<? extends Job> jobClass = jobDetail.getJobClass();
        try {
            Job job = SpringBeanUtil.getBean(jobClass);
            if (job == null) {
                log.warn("Quartz 在 spring 容器中 没有找到定时器 bean !,将 新创建 job 对象");
                job = jobClass.newInstance();
            }
            return job;

        } catch (Exception e) {
            SchedulerException se = new SchedulerException(
                    " 创建定时器失败！:"
                            + jobDetail.getJobClass().getName() + "", e);
            log.error(se.getMessage(), se);

        }
        return null;
    }
}
